<template>
  <el-form
    ref="ruleForm"
    class="login-form"
    :model="ruleForm"
    :rules="loginRules"
    label-position="left"
    autocomplete="on"
    style="
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-self: center;
    "
  >
    <el-form-item prop="telephone">
      <span class="svg-container">
        <svg-icon icon-class="user" />
      </span>
      <el-input
        ref="telephone"
        v-model="ruleForm.telephone"
        placeholder="请输入您的手机号"
        name="userName"
        type="text"
        tabindex="1"
        auto-complete="off"
      />
    </el-form-item>
    <el-form-item prop="email">
      <span class="svg-container">
        <svg-icon icon-class="user" />
      </span>
      <el-input
        ref="email"
        v-model="ruleForm.email"
        placeholder="请输入您的邮箱"
        name="usermail"
        type="text"
        tabindex="1"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item prop="emailVerify" class="captcha-formItem">
      <span class="svg-container">
        <svg-icon icon-class="verifyCode" />
      </span>
      <el-input
        v-model="ruleForm.emailVerify"
        maxlength="4"
        placeholder="请输入邮箱验证码"
        name="emailVerify"
        type="text"
        tabindex="1"
        autocomplete="off"
      />
      <el-button style="margin-right: 10px" :loading="codeLoading" :disabled="isDisable" @click="sendMsg">{{ ruleForm.codeText }}</el-button>
    </el-form-item>
    <el-form-item prop="password">
      <span class="svg-container">
        <svg-icon icon-class="password" />
      </span>
      <el-input
        :key="passwordType"
        ref="password"
        v-model.number="ruleForm.password"
        :type="passwordType"
        placeholder="请输入初始密码"
        name="password"
        tabindex="2"
        autocomplete="on"
        @keyup.native="checkCapslock"
      />
      <span class="show-pwd" @click="showPwd">
        <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
      </span>
    </el-form-item>
    <el-form-item prop="passwords">
      <span class="svg-container">
        <svg-icon icon-class="password" />
      </span>
      <el-input
        :key="passwordType"
        ref="passwords"
        v-model.number="ruleForm.passwords"
        :type="passwordType"
        placeholder="请输入确认密码"
        name="passwords"
        tabindex="2"
        autocomplete="on"
        @keyup.native="checkCapslock"
      />
      <span class="show-pwd">
        <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
      </span>
    </el-form-item>
    <el-form-item class="loginGN">
      <el-checkbox v-model="savePassBool" style="float: left;">记住密码</el-checkbox>
    </el-form-item>
    <el-button :loading="loading" type="primary" style="width:100%;" class="mt10" @click="submit">注册</el-button>
    <div style="position:relative;color: #606266;font-size: 14px;text-align: center;">
      已有账号？
      <el-button
        type="text"
        @click="toLogin"
      >点击登陆</el-button>
    </div>
  </el-form>
</template>
<script>
import { emailVerify } from '@/api/code'
import { userRegister } from '@/api/user'
export default {
  data() {
    const validateTelePhone = (rule, value, callback) => {
      const phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/ // 手机号码正则
      if (!phoneReg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    // 密码验证
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.passwords !== '') {
          this.$refs.ruleForm.validateField('passwords')
        }
        callback()
      }
    }
    // 再次确认密码验证
    var validateCheckPass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    return {
      loading: false, // 注册按钮loading
      passwordType: 'password',
      loginRules: {
        telephone: [
          { required: true, trigger: 'blur', validator: validateTelePhone }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        // password: [
        //     {required: true,message: '创建密码', trigger: 'blur'}, { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/, message: '密码必须同时包含数字与字母,且长度为 8-20位' }],
        // passwords: [
        //     {required: true,message: '确认密码',trigger: 'blur'}, {
        //     validator: (rule, value, callback) => {
        //       if (value === '') {
        //         callback(new Error('请再次输入密码'))
        //       } else if (value !== this.ruleForm.pwd) {
        //         callback(new Error('两次输入密码不一致'))
        //       } else {
        //         callback()
        //       }
        //     },
        //     trigger: 'blur'
        //   }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        passwords: [{ validator: validateCheckPass, trigger: 'blur' }],
        emailVerify: [
          { required: true, trigger: 'blur', message: '请输入验证码' },
          { min: 4, message: '长度4个字符', trigger: 'blur' }
        ]
      },
      savePassBool: false, // 是否记住密码
      intervalid: '', // 计时器
      isDisable: false,
      codeLoading: false,
      step: 2,
      active: 0,
      statusMsg: '',
      error: '',
      ruleForm: {
        telephone: '',
        email: '',
        password: '',
        passwords: '',
        emailVerify: '',
        codeText: '获取验证码'
      }
    }
  },
  watch: {
    savePassBool: {
      handler(newValue) {
        localStorage.setItem('savePassword', newValue)
      }
    }
  },
  created() {
    console.log('注册页面')
    if (localStorage.getItem('savePassword') !== undefined) {
      this.savePassBool = JSON.parse(localStorage.getItem('savePassword'))
    }
  },
  methods: {
  // 返回登录
    toLogin() {
      this.$emit('update:activeName', 'login')
    },
    // 注册 registerRegisterAdminAccount
    async registerForm() {
      this.loading = true
      const res = await userRegister({
        phone: this.ruleForm.telephone,
        email: this.ruleForm.email,
        code: this.ruleForm.emailVerify,
        password: this.ruleForm.passwords
      })
      if (res.code === 0) {
        this.$message.success('注册成功，请返回登陆页进行登陆')
        this.saveLocal() // 成功后存储到本地
        this.loading = false
        this.toLogin()
      }
    },
    // 账号存储到本地
    saveLocal() {
      if (this.savePassBool) localStorage.setItem('password', window.btoa(this.ruleForm.password))
      localStorage.setItem('userName', this.ruleForm.telephone)
    },
    // 提交
    submit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.registerForm()
        }
      })
    },
    // 获取验证码按钮
    sendMsg() {
      const self = this
      let namePass
      let emailPass
      let timerid
      console.log(timerid)
      if (timerid) {
        return false
      }
      this.$refs['ruleForm'].validateField('telephone', (valid) => {
        namePass = valid
      })
      self.statusMsg = ''
      if (namePass) {
        return false
      }
      this.$refs['ruleForm'].validateField('email', (valid) => {
        emailPass = valid
      })
      // 向后台API验证码发送
      if (!namePass && !emailPass) {
        self.codeLoading = true
        self.statusMsg = '验证码发送中...'
        emailVerify({ email: self.ruleForm.email }).then(res => {
          this.$message.success('发送成功，验证码有效期5分钟')
          let count = 60
          self.ruleForm.emailVerify = ''
          self.codeLoading = false
          self.isDisable = true
          self.statusMsg = `验证码已发送,${count--}秒后重新发送`
          timerid = window.setInterval(function() {
            self.statusMsg = `验证码已发送,${count--}秒后重新发送`
            if (count <= 0) {
              console.log('clear' + timerid)
              window.clearInterval(timerid)
              self.isDisable = false
              self.statusMsg = ''
            }
          }, 1000)
        }).catch(err => {
          this.isDisable = false
          this.statusMsg = ''
          this.codeLoading = false
          console.log(err.response.data.message)
        })
      }
    },
    // 定时器
    setCodeTimer() {
      let ss = 180 // 计时器300秒
      this.intervalid = setInterval(() => { // 设置计时器
        this.loginForm.codeText = this.formatDate(ss)
        ss--
        if (ss === 0) { // 计时器结束
          this.loginForm.codeText = '重新发送'
          // 清除计时器
          clearInterval(this.intervalid)
          this.intervalid = ''
        }
      }, 1000)
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (
          (shiftKey && key >= 'a' && key <= 'z') ||
          (!shiftKey && key >= 'A' && key <= 'Z')
        ) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    // 点击图标
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    }
  }
}
</script>

<style lang="scss" >
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: rgba(
  $color: #ea64a2,
  $alpha: 0.2,
);
$light_gray: #606266;
$cursor: #606266;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-form .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-form {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;
      font-size: 15px;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba($color: #ffffff, $alpha: 0.8);
    // ea64a2
    border-radius: 5px;
    color: #454545;
  }

  // 自己的
  .captcha-formItem {
    margin-bottom: 22px;
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
  }
  .loginGN {
    border: 0;
    background: transparent;
    margin-top: 10px;
    margin-bottom: 0px;
    .el-form-item__content {
      padding: 0 10px;
    }
    .el-checkbox__label {
      font-size: 15px;
    }
    .el-checkbox__inner {
      width: 16px;
      height: 16px;
    }
  }
}
// 验证码
// .captcha{
//   width: 100%;
//   height: 100%;
//   svg{
//     overflow: hidden;
//     width: 100%;
//     height: 100%;
//   }
// }
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-form {
  position: relative;
  width: 520px;
  max-width: 100%;
  // padding: 160px 35px 0;
  margin: 0 auto;
  overflow: hidden;
}

.tips {
  font-size: 14px;
  color: #fff;
  margin-bottom: 10px;

  span {
    &:first-of-type {
      margin-right: 16px;
    }
  }
}

.svg-container {
  padding: 6px 5px 6px 15px;
  color: $dark_gray;
  vertical-align: middle;
  width: 30px;
  display: inline-block;
}

.title-container {
  position: relative;

  .title {
    font-size: 26px;
    color: $light_gray;
    margin: 0px auto 40px auto;
    text-align: center;
    font-weight: bold;
  }
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: $dark_gray;
  cursor: pointer;
  user-select: none;
}
.button-main {
  background: 0;
  border: 0;
  margin: 20px auto;
}
</style>
